<template>
  <div class="planning-container">
    <div class="person-container">
      <LeftMenu />
      <div class="planning-content">
        <el-card>
          <ManagementTitle>
            <template #title>
              {{ plotName }}
              <el-button size="small" @click="goBack" style="margin-left: 16px;">返回楼栋列表</el-button>
            </template>
          </ManagementTitle>
          
          <!-- 小区基本信息 -->
          <div class="plot-info-card">
            <el-card shadow="never" class="info-card">
              <div class="plot-info">
                <div class="info-details">
                  <div class="detail-row">
                    <div class="detail-item">
                      <span class="detail-label">名称：</span>
                      <span class="detail-value">{{ plotInfo.name || plotName }}</span>
                    </div>
                    <div class="detail-item">
                      <span class="detail-label">所属城区：</span>
                      <span class="detail-value">{{ plotInfo.countyName || '暂无' }}</span>
                    </div>
                    <div class="detail-item">
                      <span class="detail-label">主力户型：</span>
                      <span class="detail-value">{{ plotInfo.type || '暂无' }}</span>
                    </div>
                  </div>
                  <div class="detail-row">
                    <div class="detail-item">
                      <span class="detail-label">开业时间：</span>
                      <span class="detail-value">{{ formatDate(plotInfo.listTime || '') }}</span>
                    </div>
                    <div class="detail-item">
                      <span class="detail-label">客服电话：</span>
                      <span class="detail-value">{{ plotInfo.number || '暂无' }}</span>
                    </div>
                    <div class="detail-item">
                      <span class="detail-label">项目名称：</span>
                      <span class="detail-value">{{ plotInfo.name || plotName }}</span>
                    </div>
                  </div>
                  <div class="detail-row">
                    <div class="detail-item full-width">
                      <span class="detail-label">项目地址：</span>
                      <span class="detail-value">{{ plotInfo.address || plotAddress || '暂无' }}</span>
                    </div>
                  </div>
                  <div class="detail-row" v-if="plotInfo.brief">
                    <div class="detail-item full-width">
                      <span class="detail-label">项目简介：</span>
                      <span class="detail-value">{{ plotInfo.brief }}</span>
                    </div>
                  </div>
                </div>
              </div>
            </el-card>
          </div>
          
          <!-- 小区规划标题 -->
          <div class="planning-header">
            <h3 class="planning-title">小区规划</h3>
          </div>

          <!-- 操作按钮 -->
          <div class="planning-actions">
            <el-button type="primary" @click="handleAdd">
              <el-icon><Plus /></el-icon>
              新增楼栋
            </el-button>
            <el-button
              type="danger"
              @click="handleBatchDelete"
              :disabled="selectedIds.length === 0"
            >
              <el-icon><Delete /></el-icon>
              批量删除
            </el-button>
          </div>

          <!-- 楼栋列表表格 -->
          <el-table 
            :data="buildingList" 
            border 
            style="width: 100%; margin-top: 16px;" 
            v-loading="loading"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column prop="name" label="楼栋名称" align="center" min-width="100">
              <template #default="{ row }">
                {{ row.name }}栋
              </template>
            </el-table-column>
            <el-table-column prop="unitNum" label="单元数" align="center" min-width="80">
              <template #default="{ row }">
                {{ row.unitNum }}个
              </template>
            </el-table-column>
            <el-table-column prop="floorNum" label="层数" align="center" min-width="80">
              <template #default="{ row }">
                {{ row.floorNum }}层
              </template>
            </el-table-column>
            <el-table-column prop="totalHouses" label="房屋总数" align="center" min-width="100">
              <template #default="{ row }">
                {{ row.totalHouses }}套
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" min-width="200" fixed="right">
              <template #default="{ row }">
                <el-button size="small" type="primary" @click="handleViewDetails(row)">
                  详情
                </el-button>
                <el-button size="small" type="success" @click="handleUploadImage(row)">
                  上传图片
                </el-button>
                <el-button
                  size="small"
                  type="danger"
                  @click="handleDelete(row)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 空状态 -->
          <div v-if="!loading && buildingList.length === 0" class="empty-state">
            <el-empty description="该小区暂无楼栋数据">
              <el-button type="primary" @click="handleAdd">添加楼栋</el-button>
            </el-empty>
          </div>
        </el-card>
      </div>
    </div>

    <!-- 添加楼栋对话框 -->
    <el-dialog
      v-model="showAddDialog"
      title="添加楼栋"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="buildingFormRef"
        :model="buildingForm"
        :rules="buildingFormRules"
        label-width="120px"
      >
        <el-form-item label="楼栋名称" prop="name">
          <el-input
            v-model="buildingForm.name"
            placeholder="请输入楼栋名称，如：1、A、甲等"
            maxlength="50"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="单元数" prop="unitNum">
          <el-input-number
            v-model="buildingForm.unitNum"
            :min="1"
            :max="20"
            @change="handleUnitNumChange"
          />
          <span class="form-tip">每栋楼的单元数量</span>
        </el-form-item>

        <el-form-item label="层数" prop="floorNum">
          <el-input-number
            v-model="buildingForm.floorNum"
            :min="1"
            :max="100"
          />
          <span class="form-tip">每个单元的层数</span>
        </el-form-item>

        <el-form-item label="各单元每层户数" prop="floorUserNumList">
          <div class="unit-config">
            <div
              v-for="(userNum, index) in buildingForm.floorUserNumList"
              :key="index"
              class="unit-item"
            >
              <span class="unit-label">{{ index + 1 }}单元：</span>
              <el-input-number
                v-model="buildingForm.floorUserNumList[index]"
                :min="1"
                :max="20"
                size="small"
              />
              <span class="unit-tip">户/层</span>
            </div>
          </div>
          <div class="form-tip">
            设置每个单元每层的户数，系统将自动计算总房屋数
          </div>
        </el-form-item>

        <el-form-item label="预计房屋总数">
          <span class="total-houses">{{ calculateTotalHouses() }}套</span>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCancelAdd">取消</el-button>
          <el-button type="primary" @click="handleConfirmAdd" :loading="submitLoading">
            确定添加
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 楼栋图片上传对话框 -->
    <el-dialog
      v-model="showEditDialog"
      title="上传图片&信息编辑"
      width="450px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="editFormRules"
        label-width="120px"
      >
        <el-form-item label="楼栋名称" prop="name">
          <el-input
            v-model="editForm.name"
            placeholder="请输入楼栋名称，如：1、A、甲等"
            maxlength="50"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="楼栋图片">
          <div class="building-image-upload">
            <el-upload
              :action="uploadUrl"
              :headers="uploadHeaders"
              :file-list="buildingImageList"
              :on-success="handleBuildingImageSuccess"
              :on-remove="handleBuildingImageRemove"
              :on-error="handleBuildingImageError"
              :before-upload="beforeBuildingImageUpload"
              list-type="picture-card"
              accept="image/*"
              :limit="1"
              :disabled="uploadLoading"
            >
              <el-icon v-if="!uploadLoading"><Plus /></el-icon>
              <el-icon v-else class="is-loading"><Loading /></el-icon>
            </el-upload>
            <div class="upload-tip">
              <small class="text-muted">支持jpg、png、gif等格式，单张图片不超过5MB</small>
            </div>
            <div class="image-url-preview" v-if="editForm.imageUrl">
              <small class="text-muted">当前图片：{{ editForm.imageUrl }}</small>
            </div>
          </div>
        </el-form-item>


      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCancelEdit">取消</el-button>
          <el-button type="primary" @click="handleConfirmEdit" :loading="editLoading">
            保存修改
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import LeftMenu from "@/user/LeftMenu.vue";
import { ref, reactive, onMounted } from "vue";
import ManagementTitle from "@/components/ManagementTitle.vue";
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus, Delete, Loading } from '@element-plus/icons-vue';
import axios from 'axios';
import type { PlotInfo, Building } from "@/types/formRulesInterface";

// 响应式数据
const loading = ref(false);
const buildingList = ref<Building[]>([]);
const plotInfo = ref<PlotInfo>({});
const selectedIds = ref<any[]>([]);
const showAddDialog = ref(false);
const submitLoading = ref(false);

// 修改楼栋相关
const showEditDialog = ref(false);
const editLoading = ref(false);
const currentBuilding = ref(null);

// 图片上传相关
const uploadUrl = ref('http://127.0.0.1:8080/oss/file/upload');
const uploadHeaders = ref({
  'Authorization': 'Bearer ' + localStorage.getItem('token')
});
const uploadLoading = ref(false);
const buildingImageList = ref<any[]>([]);

// 表单数据
const buildingForm = reactive({
  name: '',
  unitNum: 1,
  floorNum: 1,
  floorUserNumList: [1]
});

// 编辑表单数据
const editForm = reactive({
  id: '',
  name: '',
  imageUrl: ''
});

// 表单引用
const buildingFormRef = ref<any>(null);
const editFormRef = ref<any>(null);

// 表单验证规则
const buildingFormRules = {
  name: [
    { required: true, message: '请输入楼栋名称', trigger: 'blur' },
    { min: 1, max: 50, message: '楼栋名称长度在1到50个字符', trigger: 'blur' }
  ],
  unitNum: [
    { required: true, message: '请输入单元数', trigger: 'blur' },
    { type: 'number', min: 1, max: 20, message: '单元数必须在1到20之间', trigger: 'blur' }
  ],
  floorNum: [
    { required: true, message: '请输入层数', trigger: 'blur' },
    { type: 'number', min: 1, max: 100, message: '层数必须在1到100之间', trigger: 'blur' }
  ]
};

// 编辑表单验证规则
const editFormRules = {
  name: [
    { required: true, message: '请输入楼栋名称', trigger: 'blur' },
    { min: 1, max: 50, message: '楼栋名称长度在1到50个字符', trigger: 'blur' }
  ]
};

// URL参数
const urlParams = new URLSearchParams(window.location.search);
const plotId = ref(urlParams.get('plotId'));
const plotName = ref(decodeURIComponent(urlParams.get('plotName') || ''));
const plotAddress = ref(decodeURIComponent(urlParams.get('plotAddress') || ''));

// 工具函数
const formatDate = (dateStr: string) => {
  if (!dateStr) return '暂无';
  try {
    const date = new Date(dateStr);
    return date.toLocaleDateString('zh-CN');
  } catch {
    return '暂无';
  }
};



// API调用函数
const getPlotInfo = async () => {
  try {
    const response = await axios.get(`/rental/areaplot/${plotId.value}`);
    
    // 检查是否返回了HTML页面（代理失败）
    if (typeof response.data === 'string' && response.data.includes('<!DOCTYPE html>')) {
      // 尝试直接调用后端API
      const directResponse = await axios.get(`http://127.0.0.1:8081/rental/areaplot/${plotId.value}`);
      
      if (directResponse.data.code === 0) {
        plotInfo.value = directResponse.data.data || {};
      }
    } else if (response.data.code === 0) {
      plotInfo.value = response.data.data || {};
    }
  } catch (error) {
    console.error('获取小区信息失败:', error);
  }
};

const getBuildingList = async () => {
  loading.value = true;
  try {
    console.log('请求参数:', { plotId: plotId.value });
    console.log('请求URL:', `/rental/areabuilding/getBuildingByPlotId/${plotId.value}`);
    
    const response = await axios.get(`/rental/areabuilding/getBuildingByPlotId/${plotId.value}`, {
      timeout: 10000,
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      }
    });
    
    console.log('响应数据:', response.data);
    
    // 检查是否返回了HTML页面（代理失败）
    if (typeof response.data === 'string' && response.data.includes('<!DOCTYPE html>')) {
      console.error('代理失败，尝试直接调用后端API');
      // 尝试直接调用后端API
      const directResponse = await axios.get(`http://127.0.0.1:8081/rental/areabuilding/getBuildingByPlotId/${plotId.value}`, {
        timeout: 10000,
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json'
        }
      });
      
      console.log('直接调用响应:', directResponse.data);
      
      if (directResponse.data.code === 0) {
        buildingList.value = directResponse.data.data.list || [];
        ElMessage.success(`成功获取 ${buildingList.value.length} 栋楼栋数据`);
      } else {
        ElMessage.error(directResponse.data.msg || '获取楼栋列表失败');
      }
    } else if (response.data.code === 0) {
      buildingList.value = response.data.data.list || [];
      ElMessage.success(`成功获取 ${buildingList.value.length} 栋楼栋数据`);
    } else {
      ElMessage.error(response.data.msg || '获取楼栋列表失败');
    }
  } catch (error) {
    console.error('获取楼栋列表失败:', error);
    ElMessage.error('获取楼栋列表失败，请检查网络连接');
  } finally {
    loading.value = false;
  }
};

const saveBuildingData = async (data: any) => {
  try {
    console.log('请求数据:', data);
    console.log('请求URL:', '/rental/areabuilding');

    const response = await axios.post('/rental/areabuilding', data, {
      timeout: 10000,
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      }
    });

    console.log('响应数据:', response.data);

    // 检查是否返回了HTML页面（代理失败）
    if (typeof response.data === 'string' && response.data.includes('<!DOCTYPE html>')) {
      console.error('代理失败，尝试直接调用后端API');
      // 尝试直接调用后端API
      const directResponse = await axios.post('http://127.0.0.1:8081/rental/areabuilding', data, {
        timeout: 10000,
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json'
        }
      });

      console.log('直接调用响应:', directResponse.data);

      if (directResponse.data.code === 0) {
        ElMessage.success('楼栋添加成功');
        return true;
      } else {
        ElMessage.error(directResponse.data.msg || '添加楼栋失败');
        return false;
      }
    } else if (response.data.code === 0) {
      ElMessage.success('楼栋添加成功');
      return true;
    } else {
      ElMessage.error(response.data.msg || '添加楼栋失败');
      return false;
    }
  } catch (error) {
    console.error('添加楼栋失败:', error);
    ElMessage.error('添加楼栋失败，请检查网络连接');
    return false;
  }
};

// 删除楼栋API
const deleteBuildingData = async (ids: number[]) => {
  try {
    console.log('删除楼栋IDs:', ids);
    console.log('请求URL:', '/rental/areabuilding/logicDelete');

    const response = await axios.delete('/rental/areabuilding/logicDelete', {
      data: ids,
      timeout: 10000,
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      }
    });

    console.log('删除响应:', response.data);

    // 检查是否返回了HTML页面（代理失败）
    if (typeof response.data === 'string' && response.data.includes('<!DOCTYPE html>')) {
      console.error('代理失败，尝试直接调用后端API');
      // 尝试直接调用后端API
      const directResponse = await axios.delete('http://127.0.0.1:8081/rental/areabuilding/logicDelete', {
        data: ids,
        timeout: 10000,
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json'
        }
      });

      console.log('直接调用删除响应:', directResponse.data);

      if (directResponse.data.code === 0) {
        ElMessage.success('楼栋删除成功');
        return true;
      } else {
        ElMessage.error(directResponse.data.msg || '删除楼栋失败');
        return false;
      }
    } else if (response.data.code === 0) {
      ElMessage.success('楼栋删除成功');
      return true;
    } else {
      ElMessage.error(response.data.msg || '删除楼栋失败');
      return false;
    }
  } catch (error) {
    console.error('删除楼栋失败:', error);
    ElMessage.error('删除楼栋失败，请检查网络连接');
    return false;
  }
};

// 事件处理函数
const goBack = () => {
  window.close();
};

const handleSelectionChange = (selection: any[]) => {
  selectedIds.value = selection.map(item => item.id);
};

const handleViewDetails = (row: any) => {
  // 跳转到楼栋详情页面，传递楼栋信息
  window.open(`/landlord/building/details?buildingId=${row.id}&buildingName=${encodeURIComponent(row.name)}&plotName=${encodeURIComponent(plotName.value)}`, '_blank');
};

const handleUploadImage = (row: any) => {
  currentBuilding.value = row;
  // 填充编辑表单（只包含可编辑的字段）
  editForm.id = row.id;
  editForm.name = row.name;
  editForm.imageUrl = row.imageUrl || '';

  // 更新图片列表
  updateBuildingImageList();

  showEditDialog.value = true;
};

const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除楼栋"${row.name}栋"吗？删除后该楼栋下的所有房源信息将无法恢复！`,
      '删除确认',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );

    const success = await deleteBuildingData([row.id]);
    if (success) {
      getBuildingList(); // 重新获取列表
    }
  } catch {
    ElMessage.info('已取消删除');
  }
};

const handleBatchDelete = async () => {
  if (selectedIds.value.length === 0) {
    ElMessage.warning('请选择要删除的楼栋');
    return;
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedIds.value.length} 个楼栋吗？删除后这些楼栋下的所有房源信息将无法恢复！`,
      '批量删除确认',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );

    const success = await deleteBuildingData(selectedIds.value);
    if (success) {
      selectedIds.value = [];
      getBuildingList(); // 重新获取列表
    }
  } catch {
    ElMessage.info('已取消删除');
  }
};

const handleAdd = () => {
  showAddDialog.value = true;
  resetBuildingForm();
};

// 表单处理方法
const resetBuildingForm = () => {
  buildingForm.name = '';
  buildingForm.unitNum = 1;
  buildingForm.floorNum = 1;
  buildingForm.floorUserNumList = [1];
  if (buildingFormRef.value) {
    buildingFormRef.value.clearValidate();
  }
};

const handleUnitNumChange = (value: number) => {
  const currentLength = buildingForm.floorUserNumList.length;
  if (value > currentLength) {
    // 增加单元，默认每层1户
    for (let i = currentLength; i < value; i++) {
      buildingForm.floorUserNumList.push(1);
    }
  } else if (value < currentLength) {
    // 减少单元
    buildingForm.floorUserNumList = buildingForm.floorUserNumList.slice(0, value);
  }
};

const calculateTotalHouses = () => {
  return buildingForm.floorUserNumList.reduce((sum, userNum) => sum + userNum * buildingForm.floorNum, 0);
};

// 编辑楼栋相关方法
const resetEditForm = () => {
  editForm.id = '';
  editForm.name = '';
  editForm.imageUrl = '';
  buildingImageList.value = [];
  if (editFormRef.value) {
    editFormRef.value.clearValidate();
  }
};

const handleCancelEdit = () => {
  showEditDialog.value = false;
  resetEditForm();
};

const handleConfirmEdit = async () => {
  if (!editFormRef.value) return;

  try {
    const valid = await editFormRef.value.validate();
    if (!valid) return;

    editLoading.value = true;

    // 只提交可修改的字段：楼栋名称和图片URL
    const updateData = {
      id: editForm.id,
      name: editForm.name,
      imageUrl: editForm.imageUrl
    };

    const success = await updateBuildingData(updateData);
    if (success) {
      showEditDialog.value = false;
      resetEditForm();
      getBuildingList(); // 重新获取列表
      ElMessage.success('楼栋信息保存成功');
    }
  } catch (error) {
    console.error('保存楼栋信息失败:', error);
  } finally {
    editLoading.value = false;
  }
};

const handleCancelAdd = () => {
  showAddDialog.value = false;
  resetBuildingForm();
};

const handleConfirmAdd = async () => {
  if (!buildingFormRef.value) return;

  try {
    await buildingFormRef.value.validate();

    submitLoading.value = true;

    const buildingData = {
      name: buildingForm.name,
      plotId: parseInt(plotId.value || '0'),
      unitNum: buildingForm.unitNum,
      floorNum: buildingForm.floorNum,
      floorUserNumList: [...buildingForm.floorUserNumList]
    };

    console.log('提交楼栋数据:', buildingData);

    const success = await saveBuildingData(buildingData);
    if (success) {
      showAddDialog.value = false;
      resetBuildingForm();
      getBuildingList(); // 重新获取楼栋列表
    }
  } catch (error) {
    console.error('表单验证失败:', error);
  } finally {
    submitLoading.value = false;
  }
};

// 图片上传相关方法
const updateBuildingImageList = () => {
  if (editForm.imageUrl) {
    buildingImageList.value = [{
      uid: 1,
      name: 'building-image',
      status: 'done',
      url: editForm.imageUrl
    }];
  } else {
    buildingImageList.value = [];
  }
};

const beforeBuildingImageUpload = (file: any) => {
  const isImage = file.type.startsWith('image/');
  const isLt5M = file.size / 1024 / 1024 < 5;

  if (!isImage) {
    ElMessage.error('只能上传图片文件!');
    return false;
  }
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过 5MB!');
    return false;
  }

  uploadLoading.value = true;
  return true;
};

const handleBuildingImageSuccess = (response: any, file: any) => {
  uploadLoading.value = false;
  if (response.code === 0) {
    editForm.imageUrl = response.data.url;
    updateBuildingImageList();
    ElMessage.success('图片上传成功');
  } else {
    ElMessage.error('图片上传失败：' + response.msg);
  }
};

const handleBuildingImageRemove = (file: any) => {
  editForm.imageUrl = '';
  buildingImageList.value = [];
};

const handleBuildingImageError = (error: any) => {
  uploadLoading.value = false;
  ElMessage.error('图片上传失败，请重试');
  console.error('图片上传错误:', error);
};

// 更新楼栋数据API
const updateBuildingData = async (buildingData: any) => {
  try {
    // 只更新楼栋名称和图片URL，避免修改结构数据
    const dto = {
      id: buildingData.id,
      name: buildingData.name,
      imageUrl: buildingData.imageUrl
    };

    const response = await axios.put('/rental/areabuilding', dto);

    if (response.data.code === 0) {
      return true;
    } else {
      ElMessage.error('保存楼栋信息失败：' + response.data.msg);
      return false;
    }
  } catch (error) {
    console.error('保存楼栋信息失败:', error);
    ElMessage.error('保存楼栋信息失败，请检查网络连接');
    return false;
  }
};

// 初始化
onMounted(() => {
  if (!plotId.value) {
    ElMessage.error('缺少小区ID参数');
    return;
  }
  getPlotInfo();
  getBuildingList();
});
</script>

<style scoped>
.planning-container {
  display: flex;
  flex-direction: column;
}

.person-container {
  max-width: 1290px;
  width: 100%;
  margin: 20px auto;
  display: flex;
  justify-content: flex-start;
  align-items: flex-start;
  box-sizing: border-box;
  padding: 0 16px;
}

.planning-content {
  margin-left: 10px;
  flex: 1 1 0;
  min-width: 0;
  width: 100%;
  max-width: 100%;
}

.plot-info-card {
  margin-bottom: 20px;
}

.info-card {
  background: white;
  border: 1px solid #e4e7ed;
}

:deep(.info-card .el-card__body) {
  padding: 24px;
}

.plot-info {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.info-details {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.detail-row {
  display: flex;
  gap: 32px;
  flex-wrap: wrap;
}

.detail-item {
  display: flex;
  align-items: flex-start;
  gap: 8px;
  min-width: 200px;
}

.detail-item.full-width {
  flex: 1;
  min-width: 100%;
}

.detail-label {
  font-weight: 600;
  color: #303133;
  white-space: nowrap;
  min-width: 80px;
}

.detail-value {
  color: #606266;
  word-break: break-all;
}

.planning-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 24px 0 16px 0;
  padding: 16px 0;
  border-top: 1px solid #e4e7ed;
}

.planning-title {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.planning-actions {
  margin: 16px 0;
  display: flex;
  gap: 12px;
}

.empty-state {
  margin-top: 40px;
  text-align: center;
}

:deep(.el-card) {
  min-height: auto;
}

:deep(.el-card__body) {
  padding: 20px;
}

:deep(.el-table th) {
  background: #f5f7fa !important;
}

:deep(.el-table .el-table__cell) {
  padding: 12px 0;
}

@media (max-width: 900px) {
  .person-container {
    flex-direction: column;
    align-items: stretch;
    padding: 0 4px;
  }

  .planning-content {
    margin-left: 0;
    width: 100%;
    max-width: 100%;
  }

  .detail-row {
    flex-direction: column;
    gap: 12px;
  }

  .detail-item {
    min-width: 100%;
    flex-direction: column;
    align-items: flex-start;
    gap: 4px;
  }

  .planning-actions {
    flex-direction: column;
  }

  :deep(.el-table .el-table__cell) {
    padding: 8px 0;
  }
}

/* 添加楼栋对话框样式 */
.form-tip {
  margin-left: 8px;
  font-size: 12px;
  color: #909399;
}

.unit-config {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.unit-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.unit-label {
  min-width: 60px;
  font-size: 14px;
  color: #606266;
}

.unit-tip {
  font-size: 12px;
  color: #909399;
}

.total-houses {
  font-size: 16px;
  font-weight: 600;
  color: #409eff;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

:deep(.el-dialog__body) {
  padding: 20px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-input-number) {
  width: 120px;
}

@media (max-width: 600px) {
  .unit-config {
    gap: 8px;
  }

  .unit-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 4px;
  }

  .unit-label {
    min-width: auto;
  }
}

/* 图片上传样式 */
.building-image-upload {
  width: 100%;
}

.upload-tip {
  margin-top: 8px;
}

.image-url-preview {
  margin-top: 8px;
  padding: 6px 8px;
  background-color: #f5f7fa;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
  word-break: break-all;
}

.text-muted {
  color: #909399;
  font-size: 12px;
}

:deep(.el-upload--picture-card) {
  width: 80px;
  height: 80px;
}

:deep(.el-upload-list--picture-card .el-upload-list__item) {
  width: 80px;
  height: 80px;
}

:deep(.el-upload-list--picture-card .el-upload-list__item-thumbnail) {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

</style>
